package org.volicy.scheduled.processor;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.net.URL;
import java.util.Enumeration;

/**
 * @Author: volicy.xu
 * @Date: 2021/9/21
 */
public class ScheduledPostProcessor implements BeanPostProcessor {
    private Logger logger = LoggerFactory.getLogger(ScheduledPostProcessor.class);

    private static final String XML_PATH = "mapper/ScheduledMapper.xml";

    /**
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof MybatisPlusProperties) {
            logger.info("MybatisPlusProperties properties set.");
            MybatisPlusProperties mybatisPlusProperties = (MybatisPlusProperties) bean;
            mybatisPlusProperties.setMapperLocations(resolvingPath(mybatisPlusProperties.getMapperLocations()));
        }/*else if(bean instanceof MybatisProperties){
            logger.info("MybatisProperties properties set.");
            MybatisProperties mybatisProperties = (MybatisProperties) bean;
            mybatisProperties.setMapperLocations(resolvingPath(mybatisProperties.getMapperLocations()));
        }*/
        return bean;
    }



    /**
     *
     * @param mapperLocations
     * @return
     */
    private String[] resolvingPath(String[] mapperLocations) {
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            Enumeration<URL> urls = (classLoader != null) ? classLoader.getResources(XML_PATH) :
                    ClassLoader.getSystemResources(XML_PATH);
            String[] newMapperLocations = new String[mapperLocations.length + 1];
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                System.arraycopy(mapperLocations, 0, newMapperLocations, 0, mapperLocations.length);
                newMapperLocations[newMapperLocations.length - 1] = url.getProtocol() + ":" + url.getPath();
            }
            return newMapperLocations;
        } catch (Exception e) {
            logger.warn("MybatisPlusProperties properties is not exist.");
        }
        return mapperLocations;
    }
}
